package com.jspgou.cms.web;

import static com.jspgou.cms.Constants.REQUEST_SHOP_CONFIG_KEY;
import static com.jspgou.core.web.Constants.MODEL_PERMISSION_KEY;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jspgou.cms.entity.ShopConfig;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.ShopConfigMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.cms.service.LoginSvc;
import com.jspgou.cms.web.threadvariable.MemberThread;
import com.jspgou.common.util.CheckMobile;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.session.SessionProvider;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.SiteUtils;

/**
 * 商城信息拦截器
 * 
 * 处理Config、和登录信息
 * 
 * @author liufang
 * 
 */
public class FrontContextInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler)
			throws ServletException {
    	   	Website web = SiteUtils.getWeb(request);
    		ShopMember member = loginSvc.getMember(request, response, web);
    		// 将会员、会员组信息放入ThreadLocal，便于调用。
    		if (member != null) {
    			MemberThread.set(member);
    			CmsUtils.setMember(request, member);
    		}
    		String s = request.getServerName();
            Store store=storeMng.findByDomainName(s);
            if(store!=null){
    			if(!store.getExamine()){
    			 try {
					 response.sendRedirect("nostore.html");
				} catch (IOException e) {
					e.printStackTrace();
				}
    		    }
            	CmsUtils.setStore(request, store);
            }
        	CmsUtils.setWebsite(request, web);
        
		ShopConfig config = shopConfigMng.findById(web.getId());
		if (config == null) {
			throw new IllegalStateException(
					"no ShopConfig found in Website id=" + web.getId());
		}
		request.setAttribute(REQUEST_SHOP_CONFIG_KEY, config);
		
		Cookie cookie=CookieUtils.getCookie(request, "JSESSIONID");
		if (cookie != null) {
			Cookie c = new Cookie("JSESSIONID", cookie.getValue());
//			String ctx = request.getContextPath();
	        c.setPath("/");
			c.setDomain(web.getBaseDomain());
			response.addCookie(c);
		}
		checkEquipment(request, response);
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		Website web = SiteUtils.getWeb(request);
		ShopMember member = loginSvc.getMember(request, response, web);
		// 不控制权限时perm为null，PermistionDirective标签将以此作为依据不处理权限问题。
		if (member != null && mav != null&& !member.isSuper()
				&& mav.getModelMap() != null && mav.getViewName() != null
				&& !mav.getViewName().startsWith("redirect:")) {
			mav.getModelMap().addAttribute(MODEL_PERMISSION_KEY, member.getPerms());
			//好像是前台权限问题
		}
	}
	
	public void checkEquipment(HttpServletRequest request,HttpServletResponse response){
		String ua=(String) session.getAttribute(request, "ua");
		if(null==ua){
			try{
				String userAgent=request.getHeader("USER-AGENT").toLowerCase();
				if(null==userAgent){
					userAgent="";
				}
				if(CheckMobile.check(userAgent)){
					ua="mobile";
				}else{
					ua="pc";
				}
				session.setAttribute(request, response, "ua", ua);
			}catch(Exception e){}
		}
		if(StringUtils.isNotBlank(ua)){
			request.setAttribute("ua", ua);
		}
	}

	@Autowired
	private LoginSvc loginSvc;
	@Autowired
	private StoreMng storeMng;
	@Autowired
	private ShopConfigMng shopConfigMng;
	@Autowired
	private SessionProvider session;
}
